date()
## [1] "Fri Nov 18 19:49:19 2022"
# LOADING THE DATA

# access the MASS package
library(MASS)

# load the data
data("Boston")

# define subset of data for boxplots
box <- dplyr::select(Boston, -tax, -black)

# explore the dataset
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08205   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00
# plot distributions and matrix of the variables
boxplot(box)

boxplot(Boston$tax)

boxplot(Boston$blac)

p <- pairs(Boston)

p
## NULL

The Boston data contain information from 506 towns on factors such as crime rate, residential land, nitrogen oxides concentration, rooms per dwelling, tax rate, pupil-teacher ratio, population status and value of owner-occupied homes. Altogether 14 variables are included. No values are missing.

Variable distributions are mostly skewed. Median age of population is 77.5 years (range 2.9 to 100 years). Crime rate varies from 0.006 to 89.0, tax rate from 187 to 711 per 10,000 $, pupil-teacher ratio from 12.6 to 22.0, proportion of lower population status from 1.7% to 38.0% and nitrogen oxides concentration 0.39 to 0.87 parts per 10 million between towns.

# EXPLORING THE DATA

# access the tidyr and corrplot libraries
library(tidyr)
library(corrplot)
## corrplot 0.92 loaded
# calculate the correlation matrix and round it
cor_matrix <- cor(Boston) %>% round(digits = 2)

# print the correlation matrix
cor_matrix 
##          crim    zn indus  chas   nox    rm   age   dis   rad   tax ptratio
## crim     1.00 -0.20  0.41 -0.06  0.42 -0.22  0.35 -0.38  0.63  0.58    0.29
## zn      -0.20  1.00 -0.53 -0.04 -0.52  0.31 -0.57  0.66 -0.31 -0.31   -0.39
## indus    0.41 -0.53  1.00  0.06  0.76 -0.39  0.64 -0.71  0.60  0.72    0.38
## chas    -0.06 -0.04  0.06  1.00  0.09  0.09  0.09 -0.10 -0.01 -0.04   -0.12
## nox      0.42 -0.52  0.76  0.09  1.00 -0.30  0.73 -0.77  0.61  0.67    0.19
## rm      -0.22  0.31 -0.39  0.09 -0.30  1.00 -0.24  0.21 -0.21 -0.29   -0.36
## age      0.35 -0.57  0.64  0.09  0.73 -0.24  1.00 -0.75  0.46  0.51    0.26
## dis     -0.38  0.66 -0.71 -0.10 -0.77  0.21 -0.75  1.00 -0.49 -0.53   -0.23
## rad      0.63 -0.31  0.60 -0.01  0.61 -0.21  0.46 -0.49  1.00  0.91    0.46
## tax      0.58 -0.31  0.72 -0.04  0.67 -0.29  0.51 -0.53  0.91  1.00    0.46
## ptratio  0.29 -0.39  0.38 -0.12  0.19 -0.36  0.26 -0.23  0.46  0.46    1.00
## black   -0.39  0.18 -0.36  0.05 -0.38  0.13 -0.27  0.29 -0.44 -0.44   -0.18
## lstat    0.46 -0.41  0.60 -0.05  0.59 -0.61  0.60 -0.50  0.49  0.54    0.37
## medv    -0.39  0.36 -0.48  0.18 -0.43  0.70 -0.38  0.25 -0.38 -0.47   -0.51
##         black lstat  medv
## crim    -0.39  0.46 -0.39
## zn       0.18 -0.41  0.36
## indus   -0.36  0.60 -0.48
## chas     0.05 -0.05  0.18
## nox     -0.38  0.59 -0.43
## rm       0.13 -0.61  0.70
## age     -0.27  0.60 -0.38
## dis      0.29 -0.50  0.25
## rad     -0.44  0.49 -0.38
## tax     -0.44  0.54 -0.47
## ptratio -0.18  0.37 -0.51
## black    1.00 -0.37  0.33
## lstat   -0.37  1.00 -0.74
## medv     0.33 -0.74  1.00
# visualize the correlation matrix
corrplot(cor_matrix, method="circle", type = "upper", tl.pos = "d", tl.cex = 0.6)

The variables are mostly correlated with each other, except for the Charles River dummy variable describing if the tract bounds river or not which is correlated only mildly with the median value of owner-occupied homes (rho = 0.18). There are remarkably high correlations between age and nitrogen oxides concentration (rho = 0.73) and mean distance to main employment centres (rho = -0.75), between non-retail business acres and nitrogen oxides concentration (rho = 0.76), mean distance to main employment centres (rho = -0.71) and tax rate (rho = 0.72), between average number of rooms per dwelling and median value of owner-occupied homes (rho = 0.70), between accessibility to radial highways and tax rate (rho = 0.91), and between proportion of lower population status and median value of owner-occupied homes (rho = -0.74).

# SCALING THE DATASET AND CREATING 'CRIME' VARIABLE

# accessing library dplyr
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following object is masked from 'package:MASS':
## 
##     select
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
# center and standardize variables
boston_scaled <- scale(Boston)

# summaries of the scaled variables
summary(boston_scaled)
##       crim                 zn               indus              chas        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563   Min.   :-0.2723  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668   1st Qu.:-0.2723  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109   Median :-0.2723  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150   3rd Qu.:-0.2723  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202   Max.   : 3.6648  
##       nox                rm               age               dis         
##  Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331   Min.   :-1.2658  
##  1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366   1st Qu.:-0.8049  
##  Median :-0.1441   Median :-0.1084   Median : 0.3171   Median :-0.2790  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059   3rd Qu.: 0.6617  
##  Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164   Max.   : 3.9566  
##       rad               tax             ptratio            black        
##  Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047   Min.   :-3.9033  
##  1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876   1st Qu.: 0.2049  
##  Median :-0.5225   Median :-0.4642   Median : 0.2746   Median : 0.3808  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058   3rd Qu.: 0.4332  
##  Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372   Max.   : 0.4406  
##      lstat              medv        
##  Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 3.5453   Max.   : 2.9865
# plot distributions
boxplot(boston_scaled)

# class of the boston_scaled object
class(boston_scaled)
## [1] "matrix" "array"
# change the object to data frame
boston_scaled <- scale(Boston) %>% as.data.frame

# summary of the scaled crime rate
summary(boston_scaled$crim)
##      Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
## -0.419367 -0.410563 -0.390280  0.000000  0.007389  9.924110
# create a quantile vector of crim and print it
bins <- quantile(boston_scaled$crim)
bins
##           0%          25%          50%          75%         100% 
## -0.419366929 -0.410563278 -0.390280295  0.007389247  9.924109610
# create a categorical variable 'crime'
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE)

# look at the table of the new factor crime
table(crime)
## crime
## [-0.419,-0.411]  (-0.411,-0.39] (-0.39,0.00739]  (0.00739,9.92] 
##             127             126             126             127
# remove original crim from the dataset
boston_scaled <- dplyr::select(boston_scaled, -crim)

# add the new categorical value to scaled data
boston_scaled <- data.frame(boston_scaled, crime)

Scaling removes most of the skewness in variables.

# LINEAR DISCRIMINANT ANALYSIS

# number of rows in the Boston dataset 
n <- nrow(boston_scaled)

# choose randomly 80% of the rows
ind <- sample(n,  size = n * 0.8)

# create train set
train <- boston_scaled[ind,]

# create test set 
test <- boston_scaled[-ind,]

# save the correct classes from test data
correct_classes <- test$crime

# remove the crime variable from test data
test <- dplyr::select(test, -crime)

# linear discriminant analysis
lda.fit <- lda(crime ~ ., data = train)

# print the lda.fit object
lda.fit
## Call:
## lda(crime ~ ., data = train)
## 
## Prior probabilities of groups:
## [-0.419,-0.411]  (-0.411,-0.39] (-0.39,0.00739]  (0.00739,9.92] 
##       0.2351485       0.2549505       0.2623762       0.2475248 
## 
## Group means:
##                          zn      indus         chas        nox          rm
## [-0.419,-0.411]  1.03805753 -0.8673084 -0.065113266 -0.8969741  0.51870329
## (-0.411,-0.39]  -0.08407022 -0.3258744 -0.004759149 -0.5921620 -0.13484041
## (-0.39,0.00739] -0.39744090  0.2785509  0.247665303  0.4910288  0.07048788
## (0.00739,9.92]  -0.48724019  1.0171519 -0.036103054  1.0451102 -0.42298198
##                        age        dis        rad        tax     ptratio
## [-0.419,-0.411] -0.8913572  0.8321081 -0.6953589 -0.7215359 -0.55951665
## (-0.411,-0.39]  -0.3518447  0.3998278 -0.5425547 -0.5271189 -0.02609972
## (-0.39,0.00739]  0.4881596 -0.4348846 -0.4163054 -0.2747918 -0.34244864
## (0.00739,9.92]   0.8035884 -0.8508245  1.6377820  1.5138081  0.78037363
##                       black       lstat         medv
## [-0.419,-0.411]  0.38495934 -0.78887138  0.601314448
## (-0.411,-0.39]   0.31628070 -0.14223160  0.001077744
## (-0.39,0.00739]  0.05480403  0.08997301  0.143115732
## (0.00739,9.92]  -0.81955028  0.85849096 -0.659643108
## 
## Coefficients of linear discriminants:
##                 LD1         LD2         LD3
## zn       0.10435234  0.77940001 -1.04955970
## indus    0.02755964 -0.10018845  0.16285258
## chas    -0.08663762 -0.05477837  0.06882547
## nox      0.38595980 -0.85721244 -0.99483548
## rm      -0.09419823 -0.09116794 -0.21282756
## age      0.24678330 -0.37120746 -0.06775274
## dis     -0.08820886 -0.42222933  0.45816865
## rad      3.15999132  1.09317664  0.11783354
## tax      0.03376795 -0.23043515  0.20600241
## ptratio  0.15123659 -0.01128501 -0.10625810
## black   -0.10344385 -0.01056462  0.06821921
## lstat    0.24365608 -0.25977556  0.27634945
## medv     0.23513551 -0.42462104 -0.13771239
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9404 0.0459 0.0137
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# target classes as numeric
classes <- as.numeric(train$crime)

# plot the lda results
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 2)

In linear discriminant analysis, the highest crime class almost solely occupies one cluster and the other crime classes are mixed in the other cluster. The most influential line separators seem to be accessibility to radial highways, proportion of residential land zoned for lots over 2323 m2 and nitrogen oxides concentration, most likely implying differences between rural and urban environments. The first discriminant function separates 94.7% of the population.

# PREDICTING WITH THE LDA MODEL

# predict classes with test data
lda.pred <- predict(lda.fit, newdata = test)

# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class) %>% addmargins
##                  predicted
## correct           [-0.419,-0.411] (-0.411,-0.39] (-0.39,0.00739] (0.00739,9.92]
##   [-0.419,-0.411]              15             16               1              0
##   (-0.411,-0.39]                3             15               5              0
##   (-0.39,0.00739]               1              9               9              1
##   (0.00739,9.92]                0              0               0             27
##   Sum                          19             40              15             28
##                  predicted
## correct           Sum
##   [-0.419,-0.411]  32
##   (-0.411,-0.39]   23
##   (-0.39,0.00739]  20
##   (0.00739,9.92]   27
##   Sum             102

The LDA model works reasonably well: it correctly predicts the crime class in 69 (68%) towns.

# DISTANCES AND CLUSTERING

# access library ggplot2
library(ggplot2)

# scale dataset
boston_scaled2 <- data.frame(scale(Boston))

# euclidean distance matrix
dist_eu <- dist(boston_scaled2)

# look at the summary of the distances
summary(dist_eu)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.1343  3.4625  4.8241  4.9111  6.1863 14.3970
# manhattan distance matrix
dist_man <- dist(boston_scaled2, method = "manhattan")

# look at the summary of the distances
summary(dist_man)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.2662  8.4832 12.6090 13.5488 17.7568 48.8618
# k-means clustering
km <- kmeans(boston_scaled2, centers = 3)

# plot the Boston dataset with clusters
pairs(boston_scaled2, col = km$cluster)

pairs(boston_scaled2[1:7], col = km$cluster)

pairs(boston_scaled2[8:14], col = km$cluster)

set.seed(123)

# determine the number of clusters
k_max <- 10

# calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(boston_scaled2, k)$tot.withinss})

# visualize the results
qplot(x = 1:k_max, y = twcss, geom = 'line')

# k-means clustering
km <- kmeans(boston_scaled2, centers = 2)

# plot the Boston dataset with clusters
pairs(boston_scaled2, col = km$cluster)

pairs(boston_scaled2[1:7], col = km$cluster)

pairs(boston_scaled2[8:14], col = km$cluster)

Scaling reduces the distances and skewness of their distribution. For k-means clustering, 2 centers seem to be the best choice. One cluster seem to be associated with low crime rate, low proportion of non-retail business acres, low nitrogen oxides concentration, younger age, high mean distance to main employment centres, low accessibility to radial highways, low tax rate, high difference in race proportions and high median value of owner-occupied homes. This may refer to that clustering identifies rural areas or otherwise less densely populated areas vs. urban areas.

# BONUS SECTION: MORE ON K-MEANS CLUSTERING AND LINEAR DISCRIMINANT ANALYSIS

# k-means clustering
km2 <- kmeans(boston_scaled2, centers = 6)

# plot the Boston dataset with clusters
pairs(boston_scaled2, col = km2$cluster)

pairs(boston_scaled2[1:7], col = km2$cluster)

pairs(boston_scaled2[8:14], col = km2$cluster)

# linear discriminant analysis
lda.fit2 <- lda(km2$cluster ~ ., data = boston_scaled2)

# print the lda.fit object
lda.fit2
## Call:
## lda(km2$cluster ~ ., data = boston_scaled2)
## 
## Prior probabilities of groups:
##          1          2          3          4          5          6 
## 0.06719368 0.12252964 0.24505929 0.18972332 0.29051383 0.08498024 
## 
## Group means:
##         crim         zn      indus       chas        nox         rm        age
## 1 -0.1985497 -0.2602436  0.2799956  3.6647712  0.3830784  0.2756681  0.3721322
## 2 -0.4141953  2.3322773 -1.1788641 -0.2088275 -1.1887944  0.7188485 -1.4216721
## 3  1.1156495 -0.4872402  1.0149946 -0.2723291  0.9916473 -0.4276828  0.7515952
## 4 -0.3269211 -0.4816572  0.6406213 -0.2723291  0.4664828 -0.5082323  0.7668344
## 5 -0.3977957 -0.1563279 -0.5990216 -0.2723291 -0.6696819 -0.1686625 -0.6751063
## 6 -0.3732407 -0.1422288 -0.8310017 -0.2723291 -0.2005297  1.6901170  0.1841367
##          dis          rad        tax     ptratio       black      lstat
## 1 -0.4033382  0.001081444 -0.0975633 -0.39245849  0.17154271 -0.1643525
## 2  1.6223203 -0.666968948 -0.5535972 -0.82951564  0.35193833 -0.9665363
## 3 -0.8170870  1.659602895  1.5294129  0.80577843 -0.81154619  0.9129958
## 4 -0.5732656 -0.602637816 -0.1649468  0.21059409  0.04824716  0.5397714
## 5  0.5672190 -0.575610755 -0.6877857 -0.05330275  0.36267528 -0.3956902
## 6 -0.3232389 -0.511800977 -0.8155263 -1.10522083  0.34963036 -0.9616241
##           medv
## 1  0.573340910
## 2  0.799806470
## 3 -0.771340259
## 4 -0.505310108
## 5  0.007601824
## 6  1.719927960
## 
## Coefficients of linear discriminants:
##                  LD1         LD2         LD3          LD4         LD5
## crim     0.034508803  0.05797085 -0.16103219  0.152322830  0.01702637
## zn       0.263383770 -0.23309900 -1.54525759 -1.099430119  0.78886901
## indus   -0.073596625  0.35511069  0.27621202 -0.741302164 -0.03049072
## chas    -5.833329077 -0.28810784 -0.25366217 -0.153849858 -0.20101832
## nox      0.012019761 -0.33200265  0.08267993 -0.138256930  0.38821434
## rm       0.077523647  0.02092389 -0.05279584  0.346603115  0.54639625
## age     -0.078503080  0.10642631  0.50741330 -0.163867301  0.79431423
## dis     -0.055475885 -0.36793105 -0.33307268 -0.006313437 -0.37843684
## rad     -0.319867249  3.41804068 -1.06679562  1.629076215 -0.94341422
## tax      0.011360375 -0.30248228 -0.48448257 -0.924010759  0.59988910
## ptratio -0.010141142 -0.03367258  0.16740977 -0.504498820  0.12595753
## black   -0.007393166 -0.08886704  0.01924355  0.045161817 -0.07202500
## lstat    0.123902259  0.13351602  0.01047765  0.007966329  0.40940453
## medv     0.203273034 -0.38745314 -0.07192725  0.516887596  0.76079378
## 
## Proportion of trace:
##    LD1    LD2    LD3    LD4    LD5 
## 0.6292 0.2589 0.0730 0.0230 0.0159
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# plot the lda results
plot(lda.fit2, dimen = 2, col = km2$cluster, pch = km2$cluster)
lda.arrows(lda.fit2, myscale = 2)

Linear discriminant analysis produces three clusters, in which one cluster is occupied by k-means cluster 1, another by k-means cluster 3, and the third cluster contains the rest k-means clusters. The most influential line separators seem to be accessibility to radial highways and Charles River dummy variable. The first discriminant function separates 62.9% and the second one 25.9% of the towns.

# SUPER-BONUS SECTION: 3D PLOTTING

# access library plotly
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:MASS':
## 
##     select
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
# define a new object
model_predictors <- dplyr::select(train, -crime)

# check the dimensions
dim(model_predictors)
## [1] 404  13
dim(lda.fit$scaling)
## [1] 13  3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)

# k-means clustering
km3 <- kmeans(matrix_product, centers = 2)
km4 <- km3$cluster 

# Create 3D plot
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers')
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = train$crime)
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = km4)

The first matrix plot shows two clusters that are well separated from each other. In the second plot, one cluster is mainly occupied by the highest crime class. In the third plot, the clusters coincide fully with the k-means clustering with two centers.